package com.bjpowernode.boss.client.email;

import jakarta.annotation.Resource;
import jakarta.mail.internet.MimeMessage;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import java.io.File;

@Component
public class EmailClient {

    @Resource
    private JavaMailSender mailSender;

    public Boolean sendEmail(EmailEntity email) {
        Boolean success = false;
        if (email.getAttachFiles() == null || email.getAttachFiles().isEmpty()) {
            try {
                SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
                simpleMailMessage.setFrom(email.getFrom());
                simpleMailMessage.setTo(email.getTo());
                simpleMailMessage.setSubject(email.getSubject());
                simpleMailMessage.setText(email.getText());
                mailSender.send(simpleMailMessage);
                success = true;
            } catch (Exception e) {
                e.printStackTrace();
            }

        } else {

            try {
                MimeMessage mimeMessage = mailSender.createMimeMessage();
                MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
                helper.setFrom(email.getFrom());
                helper.setTo(email.getTo());
                helper.setSubject(email.getSubject());
                helper.setText(email.getText());
                for (AttachFile attachFile : email.getAttachFiles()) {
                    helper.addAttachment(attachFile.getFileName(), new File(attachFile.getFilePath()));
                }
                mailSender.send(helper.getMimeMessage());
                success = true;
            } catch (Exception e) {
                e.printStackTrace();
            }

        }

        return success;

    }

}
